﻿@using Blazor.Cropper;
@using CnGalWebSite.DrawingBed.Helper.Services;
@using CnGalWebSite.DrawingBed.Models.DataModels;
@inject IJSRuntime JSRuntime
@inject IFileUploadService _fileUploadService
@inject IPopupService PopupService

<MDialog Value="Dialog" ValueChanged="DialogChanged"
         Width="1000">
    <MDCard Class="image-cropper-card">
        <MCardTitle Class="text-h5">
            裁剪图片
        </MCardTitle>
        <MCardText>
            直接上传可以更加快捷地裁剪图片
        </MCardText>

        <MCardText Class="pb-0">
            @if (Dialog)
            {
                <Cropper @bind-Ratio="@ImageRatio" CropperHeight="500" InitCropWidth="200" InitCropHeight="200" MaxCropedHeight="1080" MaxCropedWidth="1920"
                         @ref="cropper"
                         PureCSharpProcessing="!OperatingSystem.IsBrowser()"
                         AspectRatio="AspectRatio"
                         RequireAspectRatio="@IsAspectRatioEnabled"
                         ImageFile="File"
                         IsImageLocked="false"
                         OnLoad="OnLoad"
                         AnimeGifEnable></Cropper>
                <MSlider @bind-Value="ImageRatio" TValue="double" Max="3" Step="0.01" Min="0.5" PrependIcon="mdi-fit-to-screen-outline "  Class="mt-3" OnPrependClick="OnReset"></MSlider>
                <CnGalWebSite.Components.Progressings.ProgressingCard Class="@(isReady?"d-none":"")" Color="white" Style="position: absolute; top: 0; bottom: 0;left: 0;right: 0; display: flex;justify-content: center;flex-direction: column;align-items: center;color:white;" />
            }


        </MCardText>
        <MCardActions Class="pb-4 pe-6 ps-6 pt-0">
            <MSpacer></MSpacer>

            <CnGalWebSite.Components.Buttons.MasaButton Text="裁剪" IsAsync="true" OnClick="DoneCrop" Icon="mdi-content-cut " Color="secondary" Rounded Class="me-4" />
            <CnGalWebSite.Components.Buttons.MasaButton Text="直接上传" IsAsync="true" OnClick="@CancelCropAsync" Icon="mdi-upload " Rounded />

        </MCardActions>
    </MDCard>
</MDialog>

@code {
    bool Dialog { get; set; }

    [Parameter]
    public EventCallback<string> OnUploadedImage { get; set; }
    [Parameter]
    public bool Gallery { get; set; }

    private Cropper cropper;

    IBrowserFile File;

    ImageAspectType Type;

    private string PreviewImagePath { get; set; }

    private bool isReady { get; set; } = false;

    private bool IsAspectRatioEnabled { get; set; } = true;

    private double AspectRatio { get; set; } = 1d;

    private double ImageRatio { get; set; } = 1;

    public void OnInputFileChange(IBrowserFile file, ImageAspectType type)
    {
        PreviewImagePath = null;

        File = file;
        IsAspectRatioEnabled = true;
        Type = type;
        switch (type)
        {
            case ImageAspectType._1_1:
                AspectRatio = 1 / 1;
                break;
            case ImageAspectType._16_9:
                AspectRatio = (double)215 / 460;
                break;
            case ImageAspectType._9_16:
                AspectRatio = (double)16 / 9;
                break;
            case ImageAspectType._4_1A2:
                AspectRatio = (double)12 / 40;
                break;
            case ImageAspectType.None:
                IsAspectRatioEnabled = false;
                break;
        }

        Dialog = true;


        StateHasChanged();
        
    }

    public void OnLoad()
    {
        isReady = true;
        
    }

    private void OnReset()
    {
        ImageRatio =1;
        StateHasChanged();
        
    }

    private async Task DoneCrop()
    {
        //获取结果
        ImageCroppedResult args = await cropper.GetCropedResult();
        //转化为字节流
        try
        {
            //上传
            var obj = await _fileUploadService.UploadImagesAsync(await args.GetDataAsync(), File.Name, Type, Gallery);
            if (obj.Uploaded == true)
            {

                PreviewImagePath = obj.Url;
            }
            else
            {
                await PopupService.ToastErrorAsync("图片上传失败", $"<{File.Name}> " + obj.Error ?? "无法图床内部传输错误");
                return;
            }
        }
        catch (Exception exc)
        {
            await PopupService.ToastErrorAsync("图片裁剪失败", "图片过于复杂无法处理，请尝试压缩图片或直接上传");
            return;
        }
        //回调
        await OnUploadedImage.InvokeAsync(PreviewImagePath);
        Dialog = false;
        isReady = false;
        StateHasChanged();

    }

    private async Task CancelCropAsync()
    {
        try
        {
            var obj = await _fileUploadService.UploadImagesAsync(File, Type, Gallery);
            if (obj.Uploaded == true)
            {

                PreviewImagePath = obj.Url;
                StateHasChanged();
            }
            else
            {
                await PopupService.ToastErrorAsync("图片上传失败", $"<{File.Name}> {obj.Error}");
                return;
            }
        }
        catch (Exception ex)
        {
            await PopupService.ToastErrorAsync("图片上传失败", "超过1MB的图片请上传到相册");            
            return;
        }
        //回调
        if (string.IsNullOrWhiteSpace(PreviewImagePath) == false)
        {
            await OnUploadedImage.InvokeAsync(PreviewImagePath);

        }

        isReady = false;
        Dialog = false;
        StateHasChanged();

    }

    public void DialogChanged(bool value)
    {
        Dialog=value;
        if(value==false)
        {
            isReady = false;
        }

        
    }
}
